package com.ljyh.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljyh.forum.dto.CommentDTO;
import com.ljyh.forum.entity.Comment;
import com.ljyh.forum.entity.Post;
import com.ljyh.forum.entity.User;
import com.ljyh.forum.mapper.CommentMapper;
import com.ljyh.forum.service.CommentService;
import com.ljyh.forum.service.PostService;
import com.ljyh.forum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评论服务实现类
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private PostService postService;

    @Autowired
    private UserService userService;

    @Override
    public List<CommentDTO> getCommentsByPostId(Long postId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post_id", postId);
        queryWrapper.orderByDesc("create_time");
        List<Comment> comments = this.list(queryWrapper);
        return convertToCommentDTOList(comments);
    }

    @Override
    public boolean publishComment(Long postId, Long userId, String content) {
        // 检查帖子是否存在
        if (postService.getById(postId) == null) {
            return false;
        }
        
        Comment comment = new Comment();
        comment.setPostId(postId);
        comment.setUserId(userId);
        comment.setContent(content);
        
        boolean result = this.save(comment);
        
        // 更新帖子的评论数
        if (result) {
            updatePostCommentCount(postId);
        }
        
        return result;
    }

    @Override
    public boolean deleteComment(Long id) {
        Comment comment = this.getById(id);
        if (comment == null) {
            return false;
        }
        
        boolean result = this.removeById(id);
        
        // 更新帖子的评论数
        if (result) {
            updatePostCommentCount(comment.getPostId());
        }
        
        return result;
    }

    @Override
    public List<Comment> getCommentsByUserId(Long userId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }

    /**
     * 更新帖子的评论数
     * @param postId 帖子ID
     */
    private void updatePostCommentCount(Long postId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post_id", postId);
        long commentCount = this.count(queryWrapper);
        
        // 更新帖子评论数
        postService.lambdaUpdate()
                .set(Post::getCommentCount, (int) commentCount)
                .eq(Post::getId, postId)
                .update();
    }
    
    /**
     * 将Comment列表转换为CommentDTO列表，并填充用户信息
     */
    private List<CommentDTO> convertToCommentDTOList(List<Comment> comments) {
        if (comments == null || comments.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有用户ID
        List<Long> userIds = comments.stream()
                .map(Comment::getUserId)
                .distinct()
                .collect(Collectors.toList());
        
        // 批量查询用户信息
        Map<Long, User> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        
        // 转换为DTO并填充用户信息
        return comments.stream().map(comment -> {
            CommentDTO dto = new CommentDTO();
            dto.setId(comment.getId());
            dto.setPostId(comment.getPostId());
            dto.setUserId(comment.getUserId());
            dto.setContent(comment.getContent());
            dto.setCreateTime(comment.getCreateTime());
            
            // 填充用户信息
            User user = userMap.get(comment.getUserId());
            if (user != null) {
                dto.setUsername(user.getUsername());
                dto.setNickname(user.getNickname());
                dto.setAvatar(user.getAvatar());
            }
            
            return dto;
        }).collect(Collectors.toList());
    }
}
